package pers.xx.sbm.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author ：xiexing
 * @description：TODO
 * @date ：2020/11/29 11:26
 */
public class TokenUtils {

    /**
     * slf4j日志
     */
    private final static Logger logger = LoggerFactory.getLogger(TokenUtils.class);

    /**
     * @description 根据ip地址和用户名生成uuid
     * @author XieXing
     * @date 2020/11/29 11:31
     */
    public static String creatToken(String ipAddress, String username) {
        Base64 base64 = new Base64();
        String text = ipAddress + "," + username;
        try {
            //编码
            byte[] textByte = text.getBytes("UTF-8");
            String encodedText = base64.encodeToString(textByte);
            return encodedText;
        } catch (UnsupportedEncodingException e) {
            logger.info("根据ip地址和用户名生成uuid失败");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @description 获取token
     * @author XieXing
     * @date 2020/11/29 11:44
     */
    public static String getToken() {
        //获取cookie里面的uuid
        String struuid = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return struuid;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("userCookie")) {
                struuid = cookie.getValue();
            }
        }
        return struuid;
    }

}
